package com.sfteam.bmw.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;
import com.sfteam.bmw.utils.StringUtils;
import com.sfteam.bmw.vo.AjaxResult;

public class CommonApi extends Controller {

	static Log logger = Log.getLog(CommonApi.class);

	private AjaxResult result = new AjaxResult();

	/**
	 * 上传文件
	 */
	public void upload() {
		String path = new SimpleDateFormat("yyyyMMdd").format(new Date());
		UploadFile file = getFile();
		File source = file.getFile();
		String fileName = file.getFileName();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		String prefix;
		if (".png".equals(extension) || ".jpg".equals(extension)
				|| ".gif".equals(extension)) {
			prefix = "img";
			fileName = StringUtils.generateString() + extension;
		} else {
			prefix = "file";
		}
		try {
			FileInputStream fis = new FileInputStream(source);
			File targetDir = new File(PathKit.getWebRootPath() + "/upload/"
					+ prefix + "/" + path);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
			File target = new File(targetDir, fileName);
			if (!target.exists()) {
				target.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(target);
			byte[] bts = new byte[300];
			while (fis.read(bts, 0, 300) != -1) {
				fos.write(bts, 0, 300);
			}
			fos.close();
			fis.close();
			result.success("/upload/" + prefix + "/" + path + "/" + fileName);
			source.delete();
		} catch (FileNotFoundException e) {
			result.addError("上传出现错误，请稍后再上传");
		} catch (IOException e) {
			result.addError("文件写入服务器出现错误，请稍后再上传");
		}
		renderJson(result);
	}
}
